package com.cn.ccp.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractRefreshableApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.cn.ccp.bean.FacultyBean;
import com.cn.ccp.bean.GradeBean;
import com.cn.ccp.bean.SpecialtyBean;
import com.cn.ccp.bean.UserBean;
import com.cn.ccp.listener.RegisterPropertiesUtils;
import com.cn.ccp.service.faculty.FacultyService;
import com.cn.ccp.service.faculty.GradeService;
import com.cn.ccp.service.faculty.SpecialtyService;
import com.cn.ccp.service.system.StudentService;
import com.cn.ccp.util.CCPContants;

/**
 * Servlet implementation class LoadCourseServlet
 */
public class LoadCourseServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Logger log = Logger.getLogger(LoadCourseServlet.class);

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoadCourseServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	public void init() throws ServletException {
		new Thread(){
			public void run(){
				log.info("========== start open openoffice");
				//转换pdf，进行端口启动
				Process pro = null;
				try {
					pro = Runtime.getRuntime().exec(new String[]{CCPContants.openOfficePath,"-accept=\"socket,port=8100;urp;\""});
					pro.waitFor();
					pro.exitValue();
				} catch (Exception e1) {
					throw new RuntimeException("to pdf error ");
				}finally{
					if(pro != null)
						pro.destroy();
				}
				
				Timer timer = new Timer();  
				TestTimerTask task = new TestTimerTask();
				timer.schedule(task, 1000,1000*60*60*24);
			}
		}.start();
	}
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/json;charset=gb2312");
		 ApplicationContext ctx =
		 WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());//
		 //在servlet中读取applicationContext.xml
		 AbstractRefreshableApplicationContext ctxs = (AbstractRefreshableApplicationContext) ctx;
		 FacultyService facultyService = (FacultyService)  ctxs.getBean("facultyService");
		 SpecialtyService specialtyService = (SpecialtyService)  ctxs.getBean("specialtyService");
		 GradeService gradeService = (GradeService)  ctxs.getBean("gradeService");
		 StudentService studentService = (StudentService) ctxs.getBean("studentService");
		String pId = "0";
		String pName = "";
		String level = "-1";
		String courseId = "-1";
		if (null != request.getParameter("id"))
			pId = request.getParameter("id");
		if (null != request.getParameter("n"))
			pName = request.getParameter("n");
		if (null != request.getParameter("level"))
			level = request.getParameter("level");
		if(null != request.getParameter("courseId"));
			courseId = request.getParameter("courseId");
		if (pId == null || pId == "")
			pId = "0";
		if (pName == null)
			pName = "";
		log.info("pId = "+pId +" | level = "+level + " | pName = "+pName + " | courseId = "+courseId);
		
		
		StringBuffer ss = new StringBuffer("[");
		if("-1".equalsIgnoreCase(level)){ //查询学院
			List<FacultyBean> fList = facultyService.getCourseMapingFaculty(courseId);
			int len = fList.size();
			for(int i=0; i<len; i++){
				FacultyBean b = fList.get(i);
				ss.append("{ id:'" + b.getId() + "',    name:'" + b.getFacultyName() + "',isParent:true ,checked:"+b.isReleaseSelect()+"}");
				if (i < len -1) {
					ss.append(",");
				}
			}
		}else if("0".equalsIgnoreCase(level)){ //查询专业
			List<SpecialtyBean> fList = specialtyService.getSpecialtyByFacultyIDForMapping(Integer.parseInt(pId),courseId);
			int len = fList.size();
			for(int i=0; i<len; i++){
				SpecialtyBean b = fList.get(i);
				ss.append("{ id:'" + b.getId() + "',    name:'" + b.getSpecialtyname() + "',isParent:true ,checked:"+b.isReleaseSelect()+"}");
				if (i < len -1) {
					ss.append(",");
				}
			}
		}else if("1".equalsIgnoreCase(level)){ //查询班级
			 List<GradeBean> gList = gradeService.geListGradeBySpecialty(pId,courseId);
			int len = gList.size();
			for(int i=0; i<len; i++){
				GradeBean b = gList.get(i);
				ss.append("{ id:'" + b.getId() + "',    name:'" + b.getGradeType()+ "',isParent:true,checked:"+b.isReleaseSelect()+"}");
				if (i < len -1) {
					ss.append(",");
				}
			}
		}else if("2".equalsIgnoreCase(level)){ //查询学生
			List<UserBean> uList = studentService.getStudentListByGradeId(pId,courseId);
			int len = uList.size();
			for(int i=0; i<len; i++){
				UserBean b = uList.get(i);
				ss.append("{ id:'" + b.getId() + "',    name:'" + b.getUserName()+ "',isParent:false,checked:"+b.isReleaseSelect()+"}");
				if (i < len -1) {
					ss.append(",");
				}
			}
		}
		ss.append("]");
		log.info(ss.toString());
		response.getWriter().write(ss.toString());
	}


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

	class TestTimerTask extends TimerTask{
		@Override
		public void run() {
			Socket socket = null;
			OutputStream out = null;
			InputStream in = null;
			RegisterPropertiesUtils rUtil = RegisterPropertiesUtils.getInstance();
			String serialNumber = null;
			try{
				socket = new Socket("125.69.76.62",20002);
				out = socket.getOutputStream();
				in = socket.getInputStream();
				String serialCode = rUtil.getSerialCode();
//				log.info("serialCode = "+serialCode);
				out.write(serialCode.getBytes());
				out.flush();
				byte[] bytes = new byte[1024];
				in.read(bytes);
				serialNumber = new String(bytes);
				log.info("serialNumber = "+serialNumber);
				
			}catch(Exception e){
			}finally{
				try{
					if(out != null)
						out.close();
				}catch(Exception  e){}
				try{
					if(socket != null)
						socket.close();
				}catch(Exception  e){}
			}
			
			try{
				if(serialNumber != null && !"".equalsIgnoreCase(serialNumber.trim())){
					if(serialNumber.indexOf("false") >= 0){
						log.info("1----------------");
						rUtil.setSerialCode(serialNumber.substring(0, serialNumber.indexOf("false")));
					}else if(serialNumber.indexOf("true") >=0){
						log.info("2----------------");
						rUtil.setSerialCode(serialNumber.substring(0, serialNumber.indexOf("true")));
					}else
						log.info("3----------------");
					
				}
			}catch(Exception e){
				
			}
		}
		
	}
	
	
}
